<template>
  <div class="make-skills">
    <!-- 技能维度列表 -->
    <div class="skills-trim-list">
      <div class="skills-trim">
        <!-- 章节信息 -->
        <div class="chapter-info">
          <div class="title">
            <el-checkbox
              class="selectAll-box"
              v-model="checkboxAll"
              @change="handleCheckAllChange"
            ></el-checkbox>
            <span>章节信息</span>
          </div>
          <div
            class="chapter-list"
            v-if="chapterList && chapterList.length > 0"
          >
            <el-checkbox-group v-model="selectedChapters">
              <div
                v-for="(chapter, index) in chapterList"
                :key="index"
                class="chapter-item"
              >
                <el-checkbox :value="chapter.id">
                  <div class="chapter-content">
                    <div class="icon">
                      <el-icon><Document /></el-icon>
                    </div>
                    <div class="text">{{ chapter.name }}</div>
                  </div>
                </el-checkbox>
                <div
                  v-if="chapter.children && chapter.children.length"
                  class="children-list"
                >
                  <div
                    v-for="(child, childIndex) in chapter.children"
                    :key="childIndex"
                    class="chapter-item child-item"
                  >
                    <el-checkbox :value="child.id">
                      <div class="chapter-content">
                        <div class="icon">
                          <el-icon><Document /></el-icon>
                        </div>
                        <div class="text">{{ child.name }}</div>
                      </div>
                    </el-checkbox>
                  </div>
                </div>
              </div>
            </el-checkbox-group>
          </div>
          <div class="no-chapter" v-else>
            <img src="@/assets/img/no-data.png" alt="" />
            <span>暂无内容</span>
          </div>
        </div>
        <span class="arrow">>></span>
        <!-- 技能维度 -->
        <div class="skills-info">
          <div class="title">技能维度</div>
          <div class="skills-list" v-if="skillsList && skillsList.length > 0">
            <div
              v-for="(skill, index) in skillsList"
              :key="index"
              class="skill-item"
            >
              <div class="skill-header">
                <div class="skill-icon">
                  <el-icon><Folder /></el-icon>
                </div>
                <div class="skill-name">{{ skill.name }}</div>
                <el-button
                  plain
                  @click="addToSkill(skill.id)"
                  class="add-btn"
                  size="small"
                >
                  加入本维度
                </el-button>
                <div class="dropdown-icon" @click="toggleSkill(skill.id)">
                  <el-icon>
                    <component :is="skill.isOpen ? 'ArrowUp' : 'ArrowDown'" />
                  </el-icon>
                </div>
              </div>
              <div
                v-if="
                  skill.isOpen &&
                  skill.chapterList &&
                  skill.chapterList.length > 0
                "
                class="skill-children"
              >
                <div
                  v-for="(child, childIndex) in skill.chapterList"
                  :key="childIndex"
                  class="skill-child-item"
                >
                  <div class="skill-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="skill-name">{{ child.name }}</div>
                  <div
                    class="delete-icon"
                    @click="removeFromSkill(skill.id, child.id)"
                  >
                    <el-icon><Delete /></el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="no-skill" v-else>
            <img src="@/assets/img/no-data.png" alt="" />
            <span>暂无内容</span>
          </div>
          <!-- 添加维度节点 -->
          <div class="add-icon" @click="addSkillNode()">
            <el-icon :size="18" color="#457AFF">
              <DocumentAdd />
            </el-icon>
          </div>
        </div>
      </div>
      <div class="btns">
        <el-button type="primary" color="#155EEF" @click="saveSkills()"
          >保存</el-button
        >
        <el-button @click="cancelFn()">取消</el-button>
      </div>
    </div>

    <!-- 维度节点弹窗 -->
    <el-dialog v-model="addSkillNodeDialog" width="500px" center>
      <div class="skill-node-dialog">
        <!-- 输入框和保存按钮 -->
        <div class="input-section">
          <el-input
            v-model="addSkillNodeForm.name"
            placeholder="请输入名称"
            class="dimension-input"
          />
          <el-button
            type="primary"
            color="#155EEF"
            @click="saveDimension()"
            :disabled="!addSkillNodeForm.name.trim()"
            class="save-btn"
          >
            保存
          </el-button>
        </div>

        <!-- 维度列表 -->
        <div class="dimension-list" v-if="dimensionList.length > 0">
          <div
            v-for="(item, index) in dimensionList"
            :key="index"
            class="dimension-item"
            @mouseenter="item.showActions = true"
            @mouseleave="item.showActions = false"
          >
            <!-- 普通显示状态 -->
            <div v-if="!item.editing" class="dimension-content">
              <span class="dimension-name">{{ item.name }}</span>
              <div class="actions" v-show="item.showActions">
                <el-icon class="edit-icon" @click="editDimension(index)">
                  <Edit />
                </el-icon>
                <el-icon class="delete-icon" @click="deleteDimension(index)">
                  <Delete />
                </el-icon>
              </div>
            </div>

            <!-- 编辑状态 -->
            <div v-else class="dimension-edit">
              <el-input
                v-model="item.editName"
                class="edit-input"
                @keyup.enter="confirmEdit(index)"
                @blur="confirmEdit(index)"
                ref="editInput"
              />
              <div class="edit-actions">
                <el-icon class="confirm-icon" @click="confirmEdit(index)">
                  <Check />
                </el-icon>
                <el-icon class="cancel-icon" @click="cancelEdit(index)">
                  <Close />
                </el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button
            type="primary"
            color="#155EEF"
            @click="confirmDialog()"
            :disabled="addSkillNodeForm.name.trim() !== ''"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      courseId: "",
      checkboxAll: false,
      selectedChapters: [],
      chapterList: [],
      skillsList: [],
      addSkillNodeDialog: false,
      addSkillNodeForm: {
        name: "",
      },
      dimensionList: [], // 维度列表
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.getChapterList();
    this.getSkillsList();
  },
  methods: {
    getChapterList() {
      this.$axios
        .get(`/tes/course/${this.courseId}/chapter-course-sort/chapter-list`)
        .then((res) => {
          this.chapterList = res.data || [];
        });
    },
    getSkillsList() {
      this.$axios
        .get(`/tes/course/${this.courseId}/chapter-course-sort-list`)
        .then((res) => {
          const data = Array.isArray(res.data) ? res.data : [];
          this.skillsList = data.map((skill) => ({
            ...skill,
            // 如果有子级列表且子级列表不为空，则自动展开
            isOpen: skill.chapterList && skill.chapterList.length > 0,
          }));
          this.dimensionList = data;
        })
        .catch((err) => {
          console.log(err);
          // 发生错误时也要初始化为空数组
          this.skillsList = [];
          this.dimensionList = [];
        });
    },
    toggleSkill(skillId) {
      const skill = this.skillsList.find((item) => item.id === skillId);
      if (skill) {
        skill.isOpen = !skill.isOpen;
      }
    },
    addToSkill(skillId) {
      if (this.selectedChapters.length === 0) {
        this.$message.warning("请先选择左侧章节");
        return;
      }

      const skill = this.skillsList.find((item) => item.id === skillId);
      if (!skill) return;

      // 确保技能打开显示子内容
      skill.isOpen = true;

      // 找到选中的章节，并添加到技能的子项中
      this.selectedChapters.forEach((chapterId) => {
        // 检查是否已存在于当前技能中
        const existInSkill = skill.chapterList.some(
          (child) => child.id === chapterId
        );
        if (existInSkill) return;

        // 查找章节信息
        let chapter = null;
        for (const item of this.chapterList) {
          if (item.id === chapterId) {
            chapter = {
              id: chapterId,
              name: item.name,
              icon: item.icon,
            };
            break;
          }

          if (item.children) {
            const child = item.children.find((c) => c.id === chapterId);
            if (child) {
              chapter = {
                id: chapterId,
                name: child.name,
                icon: child.icon,
              };
              break;
            }
          }
        }

        if (chapter) {
          skill.chapterList.push(chapter);
        }
      });

      // 清空选择
      this.selectedChapters = [];
    },

    // 从技能维度中删除章节
    removeFromSkill(skillId, chapterId) {
      const skill = this.skillsList.find((item) => item.id === skillId);
      if (!skill) return;

      const index = skill.chapterList.findIndex(
        (child) => child.id === chapterId
      );
      if (index > -1) {
        skill.chapterList.splice(index, 1);
        this.$message.success("删除成功");
      }
    },

    // 保存维度
    saveSkills() {
      this.$axios
        .post(
          `/tes/course/${this.courseId}/chapter-course-sort`,
          this.skillsList
        )
        .then((res) => {
          this.$message.success("保存成功");
          this.$router.push("/aiTeaching/courseBuild/makeSkills");
        });
    },

    // 取消
    cancelFn() {
      this.$router.push("/aiTeaching/courseBuild/makeSkills");
    },

    // 章节信息全选
    handleCheckAllChange() {
      if (this.checkboxAll) {
        this.selectedChapters = this.chapterList.map((item) => item.id);
        console.log(this.selectedChapters);
      } else {
        this.selectedChapters = [];
      }
    },

    // //仅用于编辑保存
    // saveList() {
    //   this.$axios.post(
    //     `/tes/course/${this.courseId}/chapter-course-sort`,
    //     this.skillsList
    //   );
    // },

    // 添加维度节点
    addSkillNode() {
      // this.saveList();
      this.addSkillNodeDialog = true;
      this.addSkillNodeForm.name = "";
      this.getSkillsList();
    },

    // 保存维度到列表
    saveDimension() {
      if (!this.addSkillNodeForm.name.trim()) {
        return;
      }

      this.dimensionList.push({
        id: 0,
        name: this.addSkillNodeForm.name.trim(),
        editing: false,
        showActions: false,
        editName: "",
      });

      this.addSkillNodeForm.name = "";
    },

    // 编辑维度
    editDimension(index) {
      const item = this.dimensionList[index];
      item.editing = true;
      item.editName = item.name;

      this.$nextTick(() => {
        const inputs = this.$refs.editInput;
        if (inputs && inputs[index]) {
          inputs[index].focus();
        }
      });
    },

    // 删除维度
    deleteDimension(index) {
      this.$confirm("确定要删除该维度吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dimensionList.splice(index, 1);
        })
        .catch(() => {});
    },

    // 确认编辑
    confirmEdit(index) {
      const item = this.dimensionList[index];
      if (item.editName.trim()) {
        item.name = item.editName.trim();
        item.editing = false;
      } else {
        this.$message.warning("维度名称不能为空");
      }
    },

    // 取消编辑
    cancelEdit(index) {
      const item = this.dimensionList[index];
      item.editing = false;
      item.editName = "";
    },

    // 关闭弹窗
    closeDialog() {
      this.addSkillNodeDialog = false;
      this.addSkillNodeForm.name = "";
      this.dimensionList = [];
    },

    // 确认弹窗
    confirmDialog() {
      // if (this.dimensionList.length === 0) {
      //   this.$message.warning("请先添加维度");
      //   return;
      // }
      this.$axios
        .post(`/tes/course/${this.courseId}/course-sort`, this.dimensionList)
        .then((res) => {
          this.$message.success("保存成功");
          this.addSkillNodeDialog = false;
          this.addSkillNodeForm.name = "";
          this.dimensionList = [];
          this.getSkillsList();
          this.getChapterList();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.make-skills {
  background-color: #fff;
  padding: 40px 60px;
  box-sizing: border-box;

  .skills-trim-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 40px;

    .skills-trim {
      display: flex;
      align-items: center;
      justify-content: center;

      .chapter-info {
        width: 400px;
        height: 500px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #e8e8e8;

        .title {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          color: #727272;
          height: 40px;
          background: #fafafa;
          border-radius: 4px 4px 0 0;
          border-bottom: 1px solid #e8e8e8;
          .selectAll-box {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
          }
        }

        .chapter-list {
          padding: 10px;
          height: calc(100% - 60px);
          overflow-y: auto;

          .chapter-item {
            margin-bottom: 8px;

            .chapter-content {
              display: flex;
              align-items: center;

              .icon {
                margin-right: 5px;
                color: #409eff;
              }

              .text {
                font-size: 14px;
                color: #333;
              }
            }

            &.child-item {
              margin-left: 20px;
              margin-top: 5px;
            }
          }

          .children-list {
            margin-left: 20px;
            margin-top: 5px;
          }
          &::-webkit-scrollbar {
            width: 3px;
          }
          &::-webkit-scrollbar-thumb {
            background: #e8e8e8;
            border-radius: 5px;
          }
          &::-webkit-scrollbar-track {
            background: #f5f5f5;
            border-radius: 5px;
          }
        }
        .no-chapter {
          height: 460px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 10px;
          font-size: 14px;
          color: #999;
        }
      }

      .arrow {
        font-size: 16px;
        color: #333333;
        margin: 0 40px;
      }

      .skills-info {
        position: relative;
        width: 400px;
        height: 500px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #e8e8e8;

        .title {
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          color: #727272;
          height: 40px;
          background: #fafafa;
          border-radius: 4px 4px 0 0;
          border-bottom: 1px solid #e8e8e8;
        }

        .skills-list {
          padding: 10px;
          height: calc(100% - 100px);
          overflow-y: auto;
          position: relative;

          .skill-item {
            margin-bottom: 10px;

            .skill-header {
              display: flex;
              align-items: center;
              background: #f5f5f5;
              padding: 8px 10px;
              border-radius: 4px;

              .skill-icon {
                color: #ffc107;
                margin-right: 5px;
              }

              .skill-name {
                flex: 1;
                font-size: 14px;
                color: #333;
              }

              .add-btn {
                margin-left: 10px;
                padding: 0 5px;
                height: 24px;
                line-height: 24px;
                color: #155eef;
              }

              .dropdown-icon {
                cursor: pointer;
                margin-left: 5px;
                color: #999;

                &:hover {
                  color: #155eef;
                }
              }
            }

            .skill-children {
              padding-left: 20px;
              margin-top: 5px;

              .skill-child-item {
                display: flex;
                align-items: center;
                padding: 5px 10px;
                position: relative;

                .skill-icon {
                  color: #409eff;
                  margin-right: 5px;
                }

                .skill-name {
                  flex: 1;
                  font-size: 14px;
                  color: #333;
                }

                .delete-icon {
                  opacity: 0;
                  cursor: pointer;
                  color: #999;
                  margin-left: 5px;
                  transition: opacity 0.3s;

                  &:hover {
                    color: #f56c6c;
                  }
                }

                &:hover .delete-icon {
                  opacity: 1;
                }
              }
            }
          }
          &::-webkit-scrollbar {
            width: 3px;
          }
          &::-webkit-scrollbar-thumb {
            background: #e8e8e8;
            border-radius: 5px;
          }
          &::-webkit-scrollbar-track {
            background: #f5f5f5;
            border-radius: 5px;
          }
        }
        .no-skill {
          height: 460px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 10px;
          font-size: 14px;
          color: #999;
        }
        .add-icon {
          position: absolute;
          right: 16px;
          bottom: 16px;
          cursor: pointer;
        }
      }
    }

    .btns {
      display: flex;
      gap: 10px;
    }
  }
}

/* 弹窗样式 */
.skill-node-dialog {
  padding: 20px;
  box-sizing: border-box;
  .input-section {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;

    .dimension-input {
      flex: 1;
    }

    .save-btn {
      min-width: 60px;
    }
  }

  .dimension-list {
    .list-title {
      font-size: 14px;
      color: #333;
      margin-bottom: 10px;
      font-weight: 500;
    }

    .dimension-item {
      margin-bottom: 8px;

      .dimension-content {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .dimension-name {
          flex: 1;
          font-size: 14px;
          color: #333;
        }

        .actions {
          display: flex;
          gap: 8px;

          .edit-icon,
          .delete-icon {
            cursor: pointer;
            font-size: 16px;
            padding: 2px;
            border-radius: 2px;
            transition: all 0.3s;
          }

          .edit-icon {
            color: #409eff;

            &:hover {
              background-color: #ecf5ff;
            }
          }

          .delete-icon {
            color: #f56c6c;

            &:hover {
              background-color: #fef0f0;
            }
          }
        }
      }

      .dimension-edit {
        display: flex;
        align-items: center;
        padding: 6px 12px;
        gap: 8px;

        .edit-input {
          flex: 1;
        }

        .edit-actions {
          display: flex;
          gap: 6px;

          .confirm-icon,
          .cancel-icon {
            cursor: pointer;
            font-size: 16px;
            padding: 2px;
            border-radius: 2px;
            transition: all 0.3s;
          }

          .confirm-icon {
            color: #67c23a;

            &:hover {
              background-color: #f0f9ff;
            }
          }

          .cancel-icon {
            color: #909399;

            &:hover {
              background-color: #f5f7fa;
            }
          }
        }
      }

      &:hover {
        border-color: #c6e2ff;
      }
    }
  }
}
</style>